package com.chanyachting.emall.action.yellowpage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.chanyachting.emall.domain.Yellowpagecategory;
import com.chanyachting.emall.form.YellowpagecategoryForm;
import com.chanyachting.emall.util.RequestUtil;

public class YellowpagecategoryAction extends DispatchAction {

	
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		ru.setAttribute("categoryLit", Yellowpagecategory.list());
		
		return mapping.findForward("list");
	}
	
	
	public ActionForward create(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		if(request.getMethod().equals("POST")){
			
			YellowpagecategoryForm categoryForm=(YellowpagecategoryForm)form;
			
			if(categoryForm.validate(mapping, request).isEmpty()){
				
				Yellowpagecategory category=new Yellowpagecategory();
				
				BeanUtils.copyProperties(category, categoryForm);
				
				if(category.save()){
					
					ru.setSuccessMsg();
				}else{
					
					ru.setFailMsg();
				}
			
			}
		}
		
		return mapping.findForward("create");
	}
	
	
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		int id=Integer.parseInt(ru.getParameter("id", "0"));
		
		if(request.getMethod().equals("POST")){
			
			YellowpagecategoryForm categoryForm=(YellowpagecategoryForm)form;
			
			if(categoryForm.validate(mapping, request).isEmpty()){
				
				Yellowpagecategory category=new Yellowpagecategory(id);
				
				BeanUtils.copyProperties(category, categoryForm);
				
				if(category.update()){
					
					ru.setSuccessMsg();
				}else{
					
					ru.setFailMsg();
				}
			
			}
		}
		
		ru.setAttribute("category", new Yellowpagecategory(id));
		
		return mapping.findForward("update");
	}
	
	
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		RequestUtil ru=new RequestUtil(request);
		
		int id=Integer.parseInt(ru.getParameter("id", "0"));
		
		Yellowpagecategory category=new Yellowpagecategory(id);
		
		if(category!=null){
			
			if(!category.delete()){
				
				ru.setMsg("不能删除！请先删除该分类下的所有二级分类。");
			}
		}
		
		return mapping.findForward("delete");
	}
	
	
	

}


